package com.fengwk.support.crossorigin;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fengwk.support.util.StringUtils;

/**
 * 跨源请求过滤器filter
 * 		跨域请求前浏览器会自动发出一个options请求,如果服务器的响应头部中有如下信息:
 * 		Access-Control-Allow-Origin:#允许访问的源,如http://localhost:8080
 * 		Access-Control-Allow-Methods:#允许的方法,如get,post
 * 		浏览器收到这个响应就会继续原来的请求，否则就会终止
 */
public abstract class AbstractCrossOriginFilter implements Filter {
	
	/**
	 * 源匹配
	 * @param request
	 * @return
	 */
	protected abstract boolean originMatch(String origin);
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		// Origin匹配
		String origin = request.getHeader("Origin");
		if(StringUtils.isNotBlank(origin) && originMatch(origin)) {
			response.setHeader("Access-Control-Allow-Origin", origin);
			response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
			response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
			response.setHeader("Access-Control-Allow-Credentials", "true");
		}
		chain.doFilter(servletRequest, servletResponse);
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// ignore
	}
	
	@Override
	public void destroy() {
		// ignore
	}
	
}
